package com.appspot.entourage.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.Map;

import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class HttpCli {
	public static String readURL(java.net.URL url) throws IOException {
	    FetchOptions opt = FetchOptions.Builder.doNotValidateCertificate();
	    
	    HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, opt);
	    URLFetchService service = URLFetchServiceFactory.getURLFetchService();
	    HTTPResponse response = service.fetch(request);
	    byte[] content = response.getContent();
	    return new String(content);
	}
	
	public static String postUrl(java.net.URL url, Map<String,String> headers, String content) throws IOException {
	    
		String responseStr = "";
		String message = URLEncoder.encode(content);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        
        for (Map.Entry<String,String> e : headers.entrySet()) {
        	connection.setRequestProperty(e.getKey(), e.getValue());
        }
        
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	       
        try{
	        writer.write(message);
	        writer.close();
        } finally {
            if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {}
        }
        
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        	  InputStream response = connection.getInputStream();
        	  responseStr =  response.toString();
      
        } else {
        	responseStr = "Error";
        }
        
        return responseStr;
      
	}
}
